package com.shurdroides.sintesi;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.android.c2dm.server.C2DMessaging;
import com.google.android.c2dm.server.DeviceInfo;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

import net.sf.json.JSONArray;
/**
 * Servlet de acceso al servidor que contiene todas las acciones posibles para hacer
 * @author alumneT
 *
 */
@SuppressWarnings("serial")
public class MainServlet extends HttpServlet {
	EntityManager em = (EntityManager) EMF.get().createEntityManager();
	Map<String, Region> regions = new HashMap<String, Region>();
	 private static final Logger log = Logger.getLogger(MainServlet.class.getName());
	 
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doGet(req, resp);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm =
	        C2DMessaging.getPMF(getServletContext()).getPersistenceManager();
		C2DMessaging push = C2DMessaging.get(getServletContext());

		if(req.getParameter("action")!=null){
			try{
				String region=null;
				 int action=Integer.parseInt(req.getParameter("action"));
				 if(req.getParameter("region")==null){
					 	region = "r1";
				 }else{
					 region=req.getParameter("region");
				 }
				 if (action == 0){//moverse
					Action ac = new ActionMoverse(req, em, pm, regions.get(region), push);
					ac.executeAction(regions.get(region));
					resp.getWriter().println(regions.get(region).generaString());
				 }else if(action == 1){//getRanking
					 BDHelper s= new BDHelper(em);
					 resp.getWriter().println(s.consultaRanking());					 
				 }else if(action == 2){//coger objeto
					 Action ac = new ActionCogerObjeto(req, em, pm, regions.get(region), push);
					 ac.executeAction(regions.get(region));
					 resp.getWriter().println(regions.get(region).generaString());
				 }else if(action == 3){//posicionar cueva
					 Action ac = new ActionSetCueva(req, em, regions.get(region));
					 ac.executeAction(regions.get(region));
					 resp.getWriter().println("1");
				 }else if(action == 4){//registre nou usuari
					 Action ac = new ActionNuevoUsuario(req, em, pm, regions.get(region), push);
					 ac.executeAction(regions.get(region));
					 resp.getWriter().println("1");
				 }else if(action == -1){//retorna json amb objectes y usuarios
					 resp.getWriter().println(regions.get(region).generaString());
				 }else if(action == 5){//envia un mensaje a otro usuario
					 Action ac = new ActionEnviaMensaje(req, em, pm, regions.get(region), push);
					 ac.executeAction(regions.get(region));
					 resp.getWriter().println("1");
				 }else if(action == 6){

				 }else if(action == 7){//lista usuarios para web
					 UsuarioHelper uh = new UsuarioHelper(em);
					 List<Usuario> l = new ArrayList<Usuario>();
					 l= uh.getList();
					List users = new ArrayList();
					 for (int x =0; x<l.size();x++){
						 UserMap c = new UserMap();
						 c.name= l.get(x).getNombre();
						 c.points = ""+l.get(x).getPuntos();
						 c.lat = ""+l.get(x).getLatitud_territorio();
						 c.lon = ""+l.get(x).getLongitud_territorio();
						users.add(c);
					 }
						req.setAttribute("users", users);
						req.getRequestDispatcher("map.jsp").forward(req, resp);
				 }else if(action == 20){//RESET DEL SERVIDOR (crea regiones y las repobla)
					 regions.clear();
					 Region r = new Region(em,414923,21778);
					 r.repoblarRegion();
					 regions.put("r1", r);
				 }
			}catch(IOException e){
				resp.getWriter().println("0");
		}catch(Exception e){
			StackTraceElement[] arrError;
			resp.setContentType("text/html");
			resp.getWriter().write("NOOOOOOOOOOO!!"+ e.getMessage());
			arrError=e.getStackTrace();
			for(StackTraceElement st: arrError){
				resp.getWriter().println(st.toString());
			}
		}finally{
			resp.getWriter().close();
		}
		}else{
		
		}
	
}

	public Map<String, Region> getRegions() {
		return regions;
	}

	public void setRegions(Map<String, Region> regions) {
		this.regions = regions;
	}
	


}